package com.cmhi.base.service;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInstaller;
import android.os.Build;
import android.os.IBinder;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.cmhi.base.action.HandlerAction;
import com.cmhi.base.utils.BimTools;
import com.cmhi.softmbh.IRemoteAidlInterface;
import com.cmhi.base.config.StaticConst;
import com.cmhi.base.receiver.Android_P_silenceInstallReceiver;
import com.softmbh.kellyplatform.util.AppUtils;
import com.softmbh.kellyplatform.util.CheckerUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class RemoteService extends Service implements HandlerAction {
    //静默安装成功，返回 APK 文件路径
    String resultApkFilePath = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return iRemoteAidlInterface;
    }

    private IRemoteAidlInterface.Stub iRemoteAidlInterface = new IRemoteAidlInterface.Stub() {
        @Override
        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) {
        }

        @Override
        public void setMessage(String msg) {
        }

        @Override
        public String getMessage() {
            return null;
        }

        @Override
        public void silenceInstall(String apkFilePath, String packageName) {
            AppUtils.debugLog("silenceInstall apkFilePath : " + apkFilePath + ", packageName : " + packageName);
            //silenceInstallResult("", apkFilePath);
            new Thread(() -> {
                AppUtils.debugLog(BimTools.execCmd(new String[]{"chmod", "777", apkFilePath}));
                //只能使用静默安装，不能使用非静默安装，无法获取安装结果
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {//9.0以下
                    String result = BimTools.execCmd(new String[]{"pm", "install", "-i", StaticConst.SOFT_TERMINAL_PACKAGE_NAME, "-r", apkFilePath});
                    AppUtils.debugLog("SilenceInstallReceiver result : " + result);
                    if (result.contains("Success")) {//Success 则为成功，其他均为失败
                        silenceInstallResult("Success", apkFilePath);
                    } else {
                        silenceInstallResult("Error", apkFilePath);
                    }
                } else {
//                    if (android_p_silenceInstallReceiver == null) {
//                        //动态注册安卓 9.0 静默安装成功广播接收器
//                        android_p_silenceInstallReceiver = new Android_P_silenceInstallReceiver();
//                        IntentFilter intentFilter = new IntentFilter();
//                        intentFilter.addAction("android.intent.action.PACKAGE_ADDED");
//                        intentFilter.addDataScheme("package");
//                        MyApplication.myApplication.registerReceiver(android_p_silenceInstallReceiver, intentFilter);
//                    }
                    Intent intent = new Intent(BimTools.getAppContext(), Android_P_silenceInstallReceiver.class);
                    intent.setAction(Android_P_silenceInstallReceiver.PACKAGE_INSTALLED_ACTION);
                    intent.putExtra("ApkPath", apkFilePath);
                    intent.setClassName(BimTools.getAppContext(), "Android_P_silenceInstallReceiver");
                    resultApkFilePath = apkFilePath;
                    install(BimTools.getAppContext(), apkFilePath, intent);
                }
            }).start();
        }

        @Override
        public void silenceUninstall(String packageName) {
            AppUtils.debugLog("silenceUninstall packageName : " + packageName);
            if (!CheckerUtils.isApkInstall(BimTools.getAppContext(), packageName)) {
                silenceUninstallSuccess(packageName);
            } else {
                new Thread(() -> {
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                        if (BimTools.execCmd(new String[]{"pm", "uninstall", packageName}).contains("Success")) {
                            silenceUninstallSuccess(packageName);
                        }
                    } else {
                        Intent intent = new Intent(BimTools.getAppContext(), Android_P_silenceInstallReceiver.class);
                        intent.setAction(Android_P_silenceInstallReceiver.PACKAGE_UNINSTALLED_ACTION);
                        intent.putExtra("PkgName", packageName);
                        intent.setClassName(BimTools.getAppContext(), "Android_P_silenceInstallReceiver");
                        PendingIntent pendingIntent = PendingIntent.getBroadcast(BimTools.getAppContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        PackageInstaller packageInstaller = BimTools.getAppContext().getPackageManager().getPackageInstaller();
                        packageInstaller.uninstall(packageName, pendingIntent.getIntentSender());
                    }
                }).start();
            }
        }
    };

    //Android 9.0 静默安装
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void install(Context context, String apkFilePath, Intent intent) {
        AppUtils.debugLog("apkFilePath : " + apkFilePath);
        File apkFile = new File(apkFilePath);
        PackageInstaller packageInstaller = context.getPackageManager().getPackageInstaller();
        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        sessionParams.setSize(apkFile.length());
        int sessionId = -1;
        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        AppUtils.debugLog("sessionId : " + sessionId);
        if (sessionId != -1) {
            boolean copyResult = copyInstallFile(packageInstaller, sessionId, apkFilePath);
            AppUtils.debugLog("copyResult : " + copyResult);
            if (copyResult) {
                execInstallCommand(context, packageInstaller, sessionId, intent);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private boolean copyInstallFile(PackageInstaller packageInstaller, int sessionId, String apkFilePath) {
        InputStream is = null;
        OutputStream os = null;
        PackageInstaller.Session session = null;
        boolean result = false;
        try {
            File apkFile = new File(apkFilePath);
            session = packageInstaller.openSession(sessionId);
            os = session.openWrite("base.apk", 0, apkFile.length());
            is = new FileInputStream(apkFile);
            int total = 0, read;
            byte[] buffer = new byte[1024 * 1024];
            while ((read = is.read(buffer)) != -1) {
                total += read;
                os.write(buffer, 0, read);
            }
            session.fsync(os);
            AppUtils.debugLog("streamed " + total + " bytes");
            result = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != session) {
                session.close();
            }
            try {
                if (null != os) {
                    os.close();
                }
                if (null != is) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private void execInstallCommand(Context context, PackageInstaller packageInstaller, int sessionId,
                                    Intent intent) {
        PackageInstaller.Session session = null;
        try {
            session = packageInstaller.openSession(sessionId);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            session.commit(pendingIntent.getIntentSender());
            AppUtils.debugLog("begin session");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null) {
                session.close();
            }
        }
    }


//    //安卓 9.0 静默安装成功广播接收器
//    public class Android_P_silenceInstallReceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent != null) { //安装的广播
//                String action = intent.getAction();
//                AppUtils.debugLog("Android_P_SilenceInstallReceiver action : " + action);
//                if (Intent.ACTION_PACKAGE_ADDED.equals(action)) {
//                    int status = intent.getExtras().getInt(PackageInstaller.EXTRA_STATUS);
//                    String message = intent.getExtras().getString(PackageInstaller.EXTRA_STATUS_MESSAGE);
//                    if (status == PackageInstaller.STATUS_SUCCESS) {
//                        // success
//                        AppUtils.debugLog("APP Install Success!");
//                        silenceInstallResult("Success", resultApkFilePath);
//                    } else {
//                        AppUtils.debugLog("Install failed! " + status + ", " + message);
//                        silenceInstallResult("Error", resultApkFilePath);
//                    }
//                }
//            }
//        }
//    }

    //静默安装成功
    private void silenceInstallResult(String result, String apkPath) {
        AppUtils.debugLog("silenceInstall result : " + result + ", apkPath : " + apkPath);
        Intent intent = new Intent("com.android.SilenceInstall.Over");
        intent.setPackage("com.aspirecn.jshdc.appstore");
//        intent.setPackage("com.aspirecn.combo.soft");
        intent.putExtra("Result", result);
        intent.putExtra("ApkPath", apkPath);
        intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        BimTools.getAppContext().sendBroadcast(intent);
        AppUtils.debugLog("sendBroadcast  silenceInstallResult SilenceInstall.Over result=" + result);
    }

    //静默卸载成功
    private void silenceUninstallSuccess(String PkgName) {
        if (CheckerUtils.isApkInstall(BimTools.getAppContext(), PkgName)) {
            getHandler().postDelayed(() -> silenceUninstallSuccess(PkgName), 3000);
        } else {
            AppUtils.debugLog("silenceUninstallSuccess PkgName : " + PkgName);
            Intent intent = new Intent("com.android.SilenceUninstall.Over");
            intent.setPackage("com.aspirecn.jshdc.appstore");
//            intent.setPackage("com.aspirecn.combo.soft");
            intent.putExtra("Result", "Success");
            intent.putExtra("PkgName", PkgName);
            intent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            BimTools.getAppContext().sendBroadcast(intent);
            AppUtils.debugLog("sendBroadcast  silenceUninstallSuccess SilenceInstall.Over result= Success");
        }
    }
}
